<?php

namespace PhpYes\Com;

use PhpYes\Apps\BaseApp;
use PhpYes\Yes;

class ExamplePublicUtil
{
    private static $nowTs;

    /**
     * 主要用于将 <script src="/js/user/me.js"></script>
     * 或者 <link rel="stylesheet" href="/css/user/me.css"> 等等 public 目录下的静态资源的 url
     * 转换成合适的形式
     *
     * @param string $pathUrl
     * @return string
     */
    public static function bestUrlOfPathUrl($pathUrl)
    {
        $pathUrl = empty($pathUrl) ? null : trim($pathUrl);
        if (empty($pathUrl)) {
            return '';
        }

        $env = Yes::$p->env();
        if ($env == BaseApp::ENV_PRODUCTION) {
            $lastDotPos = strrpos($pathUrl, '.');
            if ($lastDotPos === false) {
                $url = '/min' . $pathUrl . '.min';
                if (!file_exists(BASE_DIR . '/public' . $url)) {
                    $url = '/min' . $pathUrl;
                    if (!file_exists(BASE_DIR . '/public' . $url)) {
                        $url = $pathUrl;
                    }
                }
            } else {
                if ($lastDotPos) {
                    $path = substr($pathUrl, 0, $lastDotPos);
                    $ext = substr($pathUrl, $lastDotPos);
                } else {
                    $path = '';
                    $ext = $pathUrl;
                }
                $url = '/min' . $path . '.min' . $ext;
                if (!file_exists(BASE_DIR . '/public' . $url)) {
                    $url = '/min' . $pathUrl;
                    if (!file_exists(BASE_DIR . '/public' . $url)) {
                        $url = $pathUrl;
                    }
                }
            }

            return $url . '?t=' . Yes::$p->build_time();
        } else {
            if (empty(self::$nowTs)) {
                self::$nowTs = time();
            }
            return $pathUrl . '?t=' . self::$nowTs;
        }
    }

    /**
     * 主要用于将 <script src="/js/user/me.js"></script>
     * 或者 <link rel="stylesheet" href="/css/user/me.css"> 等等 public 目录下的静态资源的 url
     * 转换成 <script src="/js/user/me.js?t={{nowTs}}"></script>
     * 或者 <link rel="stylesheet" href="/css/user/me.css?t={{nowTs}}"> 这样的形式
     * 主要是为了使浏览器的缓存无效，
     * 主要用于开发调试
     *
     * @param string $pathUrl
     * @return string
     */
    public static function nowUrlOfPathUrl($pathUrl)
    {
        $pathUrl = empty($pathUrl) ? null : trim($pathUrl);
        if (empty($pathUrl)) {
            return '';
        }

        if (empty(self::$nowTs)) {
            self::$nowTs = time();
        }
        return $pathUrl . '?t=' . self::$nowTs;
    }

}